package com.ruoyi.project.system.coachPlan.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.coachPlan.domain.CoachPlan;
import com.ruoyi.project.system.coachPlan.service.ICoachPlanService;
import com.ruoyi.project.system.reservation.domain.Reservation;
import com.ruoyi.project.system.reservation.service.IReservationService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.domain.UserRole;
import com.ruoyi.project.system.user.service.IUserService;
import com.sun.jna.platform.unix.X11.XClientMessageEvent.Data;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.security.ShiroUtils;

/**
 * 预约计划信息操作处理
 * 
 * @author zhangshilin
 * @date 2019-06-26
 */
@Controller
@RequestMapping("/system/coachPlan")
public class CoachPlanController extends BaseController
{
    private String prefix = "system/coachPlan";
	
	@Autowired
	private ICoachPlanService coachPlanService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IReservationService reservationService;
	
	@RequiresPermissions("system:coachPlan:view")
	@GetMapping()
	public String coachPlan()
	{
	    return prefix + "/coachPlan";
	}
	
	/**
	 * 查询预约计划列表
	 * @throws ParseException 
	 */
	@RequiresPermissions("system:coachPlan:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(CoachPlan coachPlan) throws ParseException
	{
		//当前登录用户
		User currUser = getSysUser();
		SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		coachPlan.setIsDisable("1");//查询所有显示的数据
		//默认查询今日的数据
		if(coachPlan.getParams().get("beginTime")==null||"".equals(coachPlan.getParams().get("beginTime").toString())) {
			coachPlan.getParams().put("beginTime", simpleDateFormat1.format(new Date()));
		}
		String beginTime = coachPlan.getParams().get("beginTime").toString();
		Date beginDate = simpleDateFormat1.parse(beginTime);
		
		//startPage();不分页
        List<CoachPlan> list = coachPlanService.selectCoachPlanList(coachPlan);
        
        /*CoachPlan coachPlan2 = new CoachPlan();
        List<String> coachList =  coachPlanService.selectGroupCoach(coachPlan2);*/
        //查询要展示的教练
        List<User> coachList = new ArrayList<>();
        User user = userService.selectIsRole(currUser.getUserId(), "教练");
        if(user!=null) {
        	coachList.add(user);
        }else {
        	coachList =  userService.selectGroupCoach();
        }
        
        List<Map<String, Object>> resList = new ArrayList<>();
        
        if(coachList.size()>0) {
        	for (User coach : coachList) {
        		//取出相同教练的数据 
        		Map<String, Object> coachMap = new HashMap<>();
        		coachMap.put("coachName", coach.getUserName());
        		//查询显示时间是周几
        		Object disableDate = coachPlan.getParams().get("beginTime");
        		String week = DateUtils.getWeekOfDate(beginDate);
        		
        		coachMap.put("date", beginTime);//显示日期和星期
        		coachMap.put("week", week);
        		coachMap.put("coachPhone", coach.getPhonenumber());
        		int time8=-1,time9=-1,time10=-1,time11=-1,time12=-1,time13=-1,time14=-1,time15=-1,time16=-1,time17=-1,time18=-1,time19 = -1;
        		//显示默认的-1，页面上会显示--
        		coachMap.put("time8", time8);
				coachMap.put("time9", time9);
				coachMap.put("time10", time10);
				coachMap.put("time11", time11);
				coachMap.put("time12", time12);
				coachMap.put("time13", time13);
				coachMap.put("time14", time14);
				coachMap.put("time15", time15);
				coachMap.put("time16", time16);
				coachMap.put("time17", time17);
				coachMap.put("time18", time18);
				coachMap.put("time19", time19);
        		if(list.size()>0) {
        			for (CoachPlan coachPlan_data : list) {
            			//属于同一教练的归类到一天
    					if(coach.getUserName().equals(coachPlan_data.getCoachName())) {
    						int num = 0;
    						String time = simpleDateFormat.format(coachPlan_data.getStatrtTime());
    						String date = simpleDateFormat1.format(new Date()) + " "+ time + ":00:00";
    						Date StatrtTime = sdf.parse(date);
    						
    						Reservation reservation = new Reservation();
							reservation.setStatrtTime(StatrtTime);
							reservation.setCoachName(coach.getUserName());
							reservation.setIsDisable("1");
							List<Reservation> reservationList =  reservationService.selectReservationList(reservation);
							if(reservationList.size()>0) {
								num = reservationList.size();
							}
    						
    						switch (time) {
    						case "08":
    							time8 = num;
    							coachMap.put("time8", time8);
    							break;
    						case "09":
    							time9 = num;
    							coachMap.put("time9", time9);
    							break;
    						case "10":
    							time10 = num;
    							coachMap.put("time10", time10);
    							break;
    						case "11":
    							time11 = num;
    							coachMap.put("time11", time11);
    							break;
    						case "12":
    							time12 = num;
    							coachMap.put("time12", time12);
    							break;
    						case "13":
    							time13 = num;
    							coachMap.put("time13", time13);
    							break;
    						case "14":
    							time14 = num;
    							coachMap.put("time14", time14);
    							break;
    						case "15":
    							time15 = num;
    							coachMap.put("time15", time15);
    							break;
    						case "16":
    							time16 = num;
    							coachMap.put("time16", time16);
    							break;
    						case "17":
    							time17 = num;
    							coachMap.put("time17", time17);
    							break;
    						case "18":
    							time18 = num;
    							coachMap.put("time18", time18);
    							break;
    						case "19":
    							time19 = num;
    							coachMap.put("time19", time19);
    							break;

    						default:
    							break;
    						}
    						
    					}
    				}
        		}
        		
        		resList.add(coachMap);

				
			}
        }
		return getDataTable(resList);
	}
	
	
	/**
	 * 导出预约计划列表
	 */
	@RequiresPermissions("system:coachPlan:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CoachPlan coachPlan)
    {
    	List<CoachPlan> list = coachPlanService.selectCoachPlanList(coachPlan);
        ExcelUtil<CoachPlan> util = new ExcelUtil<CoachPlan>(CoachPlan.class);
        return util.exportExcel(list, "coachPlan");
    }
	
	/**
	 * 新增预约计划
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存预约计划
	 */
	@RequiresPermissions("system:coachPlan:add")
	@Log(title = "预约计划", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(CoachPlan coachPlan)
	{		
		return toAjax(coachPlanService.insertCoachPlan(coachPlan));
	}

	/**
	 * 修改预约计划
	 */
	@GetMapping("/edit/{coachplanId}")
	public String edit(@PathVariable("coachplanId") Integer coachplanId, ModelMap mmap)
	{
		CoachPlan coachPlan = coachPlanService.selectCoachPlanById(coachplanId);
		mmap.put("coachPlan", coachPlan);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存预约计划
	 */
	@RequiresPermissions("system:coachPlan:edit")
	@Log(title = "预约计划", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(CoachPlan coachPlan)
	{		
		return toAjax(coachPlanService.updateCoachPlan(coachPlan));
	}
	
	/**
	 * 删除预约计划
	 */
	@RequiresPermissions("system:coachPlan:remove")
	@Log(title = "预约计划", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(coachPlanService.deleteCoachPlanByIds(ids));
	}
	
	@RequiresPermissions("system:coachPlan:edit")
	@Log(title = "预约计划", businessType = BusinessType.UPDATE)
	@PostMapping( "/updateCoachPlan")
	@ResponseBody
	public AjaxResult updateCoachPlan(@Param("phone") String phone,@Param("date") Date date,@Param("timeValue") String timeValue,@Param("value") String value) {

		// 获取当前的用户信息
		User currentUser = ShiroUtils.getSysUser();
		// 获取当前的用户名称
		String userName = currentUser.getUserName();
		
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
		Calendar ca = Calendar.getInstance();
		//去掉timevalue中的time字符,然后转换成第几个小时来把开始时间放进CoachPlan查询
		timeValue = timeValue.replace("time", "");
		int addtime = Integer.parseInt(timeValue);
		//开始和结束时间
		long startTime = date.getTime()+addtime*60*60*1000;
		long endTime = date.getTime()+(addtime+1)*60*60*1000;
		Date dateStart = new Date(startTime);
		Date dateEnd = new Date(endTime);
		try {
			//查询条件
			CoachPlan coachPlan = new CoachPlan();
			coachPlan.setStatrtTime(dateStart);
			coachPlan.setCoachPhone(phone);
			coachPlan.setIsDisable("1");
			List<CoachPlan> list =  coachPlanService.selectCoachPlanList(coachPlan);
			//处理返回值
			if(list.size()>0) {
				//如果大于0,属于可预约>>不可预约
				
				//先判断教练当前时间是否有已预约学员
				Reservation reservationVer = new Reservation();
				reservationVer.setCoachPhone(phone);//手机号确定教练
				reservationVer.setStatrtTime(dateStart);//开始时间确定是哪条记录
				reservationVer.setIsDisable("1");//可显示的数据
				List<Reservation> reservationList = reservationService.selectReservationList(reservationVer);
				if(reservationList.size()>0) {
					Reservation reservation = reservationList.get(0);
					return AjaxResult.error("当前教练已有预约学员:"+reservation.getUserName()+",取消计划不可用");
				}
				
				//如果可以取消当前教练的预约记录，那么把数据setIsDisable置为0不可现
				int rest = 0;
				for (CoachPlan coachPlan2 : list) {
					coachPlan2.setIsDisable("0");
					coachPlan2.setUpdateBy(ShiroUtils.getSysUser().getUserName());
					coachPlan2.setUpdateTime(now);
					coachPlanService.updateCoachPlan(coachPlan2);
					rest++;
				}
				if(rest>0) {
					return AjaxResult.success();
				}else{
					return AjaxResult.error();
				}
			}else {
				//如果没有值,新建一条可预约的数据
				User user = userService.selectUserByPhoneNumber(phone);
				CoachPlan coachPlanIn = new CoachPlan();
				coachPlanIn.setCoachName(user.getUserName());
				coachPlanIn.setCoachPhone(user.getPhonenumber());
				coachPlanIn.setStatrtTime(dateStart);
				coachPlanIn.setEndTime(dateEnd);
				coachPlanIn.setCreateBy(userName);
				coachPlanIn.setCreateTime(now);
				coachPlanIn.setUpdateBy(userName);
				coachPlanIn.setUpdateTime(now);
				coachPlanIn.setIsDisable("1");//可显示
				coachPlanIn.setNowDate(dateFormat1.format(date));
				//coachPlanIn.setStatus("0");//默认0
				int rest = coachPlanService.insertCoachPlan(coachPlanIn);
				return AjaxResult.success();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return AjaxResult.success();
		
		
	}
	
}
